package BanyuanClub.Study.Day0305;

import java.io.*;
import java.nio.file.FileStore;

/**
 * 运用IO和File对文件进行切割
 */
public class SplitFile {

    public static void main(String[] args) {
        //创建一个新的文件指向javase/ddd.txt
        File file = new File("javase/ddd.txt");
        //创建两个IO流
        try (BufferedInputStream br1 = new BufferedInputStream
                (new FileInputStream("javase/ddd.txt"));
             BufferedInputStream br2 = new BufferedInputStream
                     (new FileInputStream("javase/ddd.txt"));
             BufferedOutputStream bw1 = new BufferedOutputStream(
                     new FileOutputStream("ddd1.txt"));
             BufferedOutputStream bw2 = new BufferedOutputStream(
                     new FileOutputStream("ddd2.txt"))
        ){
            //得到文件大小
            long fileLong = file.length();
            //计算分割后文件大小
            long after = fileLong/2;
            //剩余文件大小
            long before = after;
            byte[] by = new byte[8];
            //前半
            while (after > 0){
                //每次输出字节数
                int len = br1.read(by);
                //当多次循环后剩余字节数为after且小于byte数时，输出after字节数
                bw1.write(by,0,(int)(after < len ? after:len));
                bw1.flush();
                //每循环一次减去byte数组定义的数
                after -= len;
            }
            //后半
            //跳过前面的字节数
            br2.skip(before);
            int len;
            while ((len = br2.read(by)) != -1){
                bw2.write(by,0,len);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
